﻿using Microsoft.EntityFrameworkCore;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace MyWeb.ServiceBus.Services.Impl
{
    public class BaseEFService<Entity> : IBaseService<Entity> where Entity : class
    {
        private readonly Context db;
        private readonly DbSet<Entity> entities;
        public BaseEFService(Context context)
        {
            db = context;
            //db = context.GetDbContext();
            entities = context.Set<Entity>();
        }
        public long Add(Entity t)
        {
            db.Add(t);
            return db.SaveChanges();
        }

        public async Task<long> AddAsync(Entity t)
        {
            db.Add(t);
            return await db.SaveChangesAsync();
        }

        public int Delete(Entity t)
        {
            db.Remove(t);
            return db.SaveChanges();
        }

        public Task<int> DeleteAsync(Entity t)
        {
            db.Remove(t);
            return db.SaveChangesAsync();
        }

        public int Edit(Entity t)
        {
            db.Update(t);
            return db.SaveChanges();
        }

        public Task<int> EditAsync(Entity t)
        {
            db.Update(t);
            return db.SaveChangesAsync();
        }

        public List<Entity> Query(Expression<Func<Entity, bool>> where)
        {
            var data = entities.Where(where).ToList();
            return data;
        }

        public Task<List<Entity>> QueryAsync(Expression<Func<Entity, bool>> where)
        {
            return entities.Where(where).ToListAsync();
        }
        public List<Entity> QueryPage(Expression<Func<Entity, bool>> where, out long count, int page = 1, int pageSize = 20)
        {
            count = entities.Where(where).LongCount();
            var query = entities.Where(where).Skip((page - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }
        public List<Entity> QueryPage(out long count, int page = 1, int pageSize = 20)
        {
            count = entities.LongCount();
            var query = entities.Skip((page - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }

        public Task<List<Entity>> QueryPageAsync(out long count, int page = 1, int pageSize = 20)
        {
            count = entities.LongCount();
            var query = entities
                .Skip((page - 1) * pageSize)
                .Take(pageSize);
            return query.ToListAsync();
        }
    }
}
